package com.hue.gulimail.gulimailproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hue.common.utils.R;
import com.hue.gulimail.gulimailproduct.entity.SkuImagesEntity;
import com.hue.gulimail.gulimailproduct.entity.SkuSaleAttrValueEntity;
import com.hue.gulimail.gulimailproduct.entity.SpuInfoDescEntity;
import com.hue.gulimail.gulimailproduct.feign.SeckillFeignService;
import com.hue.gulimail.gulimailproduct.service.*;
import com.hue.gulimail.gulimailproduct.vo.SeckillRedisVo;
import com.hue.gulimail.gulimailproduct.vo.SkuItemSaleAttr;
import com.hue.gulimail.gulimailproduct.vo.SkuItemVo;
import com.hue.gulimail.gulimailproduct.vo.SpuItemAttrGroup;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.common.utils.PageUtils;
import com.hue.common.utils.Query;

import com.hue.gulimail.gulimailproduct.dao.SkuInfoDao;
import com.hue.gulimail.gulimailproduct.entity.SkuInfoEntity;


/**
 * @author yfq
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SeckillFeignService seckillFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils querySkuInfoPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("sku_id", key).or().eq("spu_id", key).or().like("sku_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min) && new BigDecimal(min).compareTo(BigDecimal.valueOf(0)) == 1) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && new BigDecimal(max).compareTo(BigDecimal.valueOf(0)) == 1) {
            wrapper.le("price", max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuInfoListBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return list(wrapper);
    }

    @Override
    public SkuItemVo getSkuItemVo(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        //使用异步编排来优化查询步骤,5个步骤的依赖关系:3,4,5-->1

        //1.开启异步任务来获取SkuInfo
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, threadPoolExecutor);

        //skuInfo获取到后需要执行3个异步任务
        //2.根据spuId获取SpuInfoDesc
        CompletableFuture<Void> spuInfoDescFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(skuInfo.getSpuId());
            skuItemVo.setSpuInfoDesc(spuInfoDesc);
        }, threadPoolExecutor);

        //3.根据spuId获取sku的销售属性
        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            List<SkuItemSaleAttr> saleAttrs = skuSaleAttrValueService.getSkuItemSaleAttrBySkuId(skuInfo.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        //4.根据spuId和catalogId获取spu的规格参数
        CompletableFuture<Void> spuItemAttrGroupFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            List<SpuItemAttrGroup> spuItemAttrGroups = productAttrValueService.getSpuItemAttrGroupBySpuId(skuInfo.getSpuId(), skuInfo.getCatalogId());
            skuItemVo.setSpuItemAttrGroups(spuItemAttrGroups);
        }, threadPoolExecutor);

        //5.开启异步任务来获取SkuImages
        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.getBySkuId(skuId);
            skuItemVo.setSkuImages(skuImages);
        }, threadPoolExecutor);

        //6.查询skuInfo的秒杀信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.skuInfoSeckill(skuId);
            if ((Integer) r.get("code") == 0) {
                SeckillRedisVo seckillRedisVo = r.getData(new TypeReference<SeckillRedisVo>() {
                });
                skuItemVo.setSeckillVo(seckillRedisVo);
            }
        }, threadPoolExecutor);

        //等待6个异步任务完成
        CompletableFuture.allOf(spuInfoDescFuture, saleAttrFuture, spuItemAttrGroupFuture, skuImagesFuture, seckillFuture).get();

        //不使用异步编排
//        //1.获取SkuInfo
//        SkuInfoEntity skuInfo = getById(skuId);
//        skuItemVo.setSkuInfo(skuInfo);
//
//        //2.根据skuId获取SkuImages
//        List<SkuImagesEntity> skuImagesList = skuImagesService.getBySkuId(skuId);
//        skuItemVo.setSkuImages(skuImagesList);
//
//        //3.根据spuId获取SpuInfoDesc
//        SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(skuInfo.getSpuId());
//        skuItemVo.setSpuInfoDesc(spuInfoDesc);
//
//        //4.sku的销售属性
//        List<SkuItemSaleAttr> skuSaleAttrValues = skuSaleAttrValueService.getSkuItemSaleAttrBySkuId(skuInfo.getSpuId());
//        skuItemVo.setSaleAttrs(skuSaleAttrValues);
//
//        //5.spu的规格参数
//        List<SpuItemAttrGroup> spuItemAttrGroups = productAttrValueService.getSpuItemAttrGroupBySpuId(skuInfo.getSpuId(), skuInfo.getCatalogId());
//        skuItemVo.setSpuItemAttrGroups(spuItemAttrGroups);

        return skuItemVo;
    }
}
